import * as API_Members from '../../../api/members'
import {Foundation}  from '../../../ui-utils/index.js'
const app = getApp();

Page({
  data: {
    tabList: [
      {
        type: 1,
        name: '未使用'
      },
      {
        type: 2,
        name: '已使用'
      },
      {
        type: 3,
        name: '已过期'
      }
    ],
    showType: 1,
    couponsList:[],
    params: {
      page_no: 1,
      page_size: 10,
      status: 1
    },
    finished:false,
    scrollHeight: '',
    scrollTop: 0,//滚动高度
    showGoTop: false,//显示返回顶部按钮
    pageCount: 0
  },
  onLoad: function (options) {
    let query = wx.createSelectorQuery();
    query.select('.tab-switch').boundingClientRect(rect => {
      this.setData({
        scrollHeight: wx.getSystemInfoSync().windowHeight - rect.height
      });
    }).exec();
    this.getCoupons();
  },
  // 状态切换
  switchTab: function (e) {
    const { type } = e.currentTarget.dataset;
    if (type !== this.data.showType) {
      this.setData({
        'params.status': type,
        'params.page_no': 1,
        showType: type,
        couponsList: []
      });
      this.getCoupons();
    };
  },
  // 获取优惠券
  getCoupons: function () {
    const params = this.data.params;
    API_Members.getCoupons(params).then(res => {
      let _pageCount = Math.ceil(res.data_total / this.data.params.page_size)
      this.setData({ pageCount: _pageCount })
      const data = res.data
      if(data && data.length){
        data.forEach(key=>{
          key.start_time = Foundation.unixToDate(key.start_time, 'yyyy-MM-dd')
          key.end_time = Foundation.unixToDate(key.end_time, 'yyyy-MM-dd')
        })
        this.setData({
          couponsList: this.data.couponsList.concat(data)
        })
      }else{
        this.setData({ finished: true })
      }
    })
  },
  // 立即使用优惠券
  goUse: function (e) {
    const { seller } = e.currentTarget.dataset;
    if (!seller && seller !== 0) {
      wx.switchTab({
        url: '/pages/index/index',
      });
    } else {
      wx.navigateTo({
        url: `/pages/shop/shop_id/shop_id?id=${seller}`
      })
    };
  },
  // 加载更多
  loadMore: function () {
    if (!this.data.finshed) {
      this.setData({"params.page_no": this.data.params.page_no + 1})
      if (this.data.pageCount >= this.data.params.page_no) {
        this.getCoupons();
      };
    }  
  },
  // 滚动显示置顶按钮
  scroll: function (e) {
    if (e.detail.scrollTop > 200) {
      this.setData({ showGoTop: true })
    } else {
      this.setData({ showGoTop: false })
    };
  },
  // 返回顶部
  goTop: function () {
    this.setData({ scrollTop: 0 })
  }
})